#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QProgressBar>
#include <QProgressDialog>
#include <QPushButton>
#include <QLabel>
#include <QTimer>
#include <QMessageBox>

class ProgressExample : public QWidget
{
    Q_OBJECT

public:
    ProgressExample(QWidget* parent = nullptr) : QWidget(parent)
    {
        setupUI();
        setupConnections();
    }

private slots:
    void startTask()
    {
        // 重置进度条
        progressValue = 0;
        embeddedProgress->setValue(0);

        // 显示进度对话框
        progressDialog->setLabelText("正在处理数据，请稍候...");
        progressDialog->setValue(0);
        progressDialog->show();

        // 启动定时器模拟任务
        timer->start(50);
    }

    void updateProgress()
    {
        progressValue += 1;

        // 更新嵌入式进度条
        embeddedProgress->setValue(progressValue);

        // 更新对话框进度条
        progressDialog->setValue(progressValue);

        // 更新状态标签
        statusLabel->setText(QString("当前进度: %1%").arg(progressValue));

        // 检查是否完成
        if (progressValue >= 100) {
            timer->stop();
            QMessageBox::information(this, "完成", "任务已完成!");
        }
    }

    void cancelTask()
    {
        timer->stop();
        QMessageBox::information(this, "取消", "任务已取消");
    }

private:
    void setupUI()
    {
        QVBoxLayout* mainLayout = new QVBoxLayout(this);

        // 嵌入式进度条部分
        QLabel* embeddedLabel = new QLabel("嵌入式进度条:");
        embeddedProgress = new QProgressBar();
        embeddedProgress->setRange(0, 100);
        embeddedProgress->setValue(0);
        embeddedProgress->setFormat("%p%");

        // 状态标签
        statusLabel = new QLabel("当前进度: 0%");

        // 按钮
        startButton = new QPushButton("开始任务");
        QPushButton* resetButton = new QPushButton("重置");

        QHBoxLayout* buttonLayout = new QHBoxLayout();
        buttonLayout->addWidget(startButton);
        buttonLayout->addWidget(resetButton);

        mainLayout->addWidget(embeddedLabel);
        mainLayout->addWidget(embeddedProgress);
        mainLayout->addWidget(statusLabel);
        mainLayout->addLayout(buttonLayout);

        // 创建进度对话框
        progressDialog = new QProgressDialog("处理中...", "取消", 0, 100, this);
        progressDialog->setWindowTitle("任务进度");
        progressDialog->setAutoClose(true);
        progressDialog->setAutoReset(true);

        // 创建定时器
        timer = new QTimer(this);
    }

    void setupConnections()
    {
        connect(startButton, &QPushButton::clicked, this, &ProgressExample::startTask);
        connect(timer, &QTimer::timeout, this, &ProgressExample::updateProgress);
        connect(progressDialog, &QProgressDialog::canceled, this, &ProgressExample::cancelTask);
    }

    QProgressBar* embeddedProgress;
    QProgressDialog* progressDialog;
    QPushButton* startButton;
    QLabel* statusLabel;
    QTimer* timer;
    int progressValue = 0;
};
